<template>
  <div>
    <el-dialog
      :title="!dataForm.id ? '新增' : '修改'"
      :close-on-click-modal="false"
      :visible.sync="visible"
    >
      <el-form
        :model="dataForm"
        :rules="dataRule"
        ref="dataForm"
        label-width="80px"
      >
        <el-form-item label="角色名" prop="reName">
          <el-input v-model="dataForm.reName" placeholder="角色名"></el-input>
        </el-form-item>
        <el-form-item label="授权识别" prop="authority">
          <el-cascader
            :options="routs"
            v-model="dataForm.routids"
            :props="props"
            @change="changedata"
            clearable
          ></el-cascader>
        </el-form-item>
        <el-form-item label="权限" prop="purview">
          <el-cascader
            :options="purviews"
            v-model="userpurviews"
            :props="purviewSprops"
            @change="changePurview"
            data="name"
            clearable
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import api from "@/api/role";
import rout from "@/api/routing";
export default {
  data() {
    return {
      purviews: [],
      userpurviews:[],
      purviewSprops: {
        value: "id",
        label: "name",
        checkStrictly: true,
        children: "list",
        multiple: true,
      },
      props: {
        value: "id",
        label: "menuName",
        checkStrictly: true,
        children: "children",
        multiple: true,
      },
      routs: [],
      visible: false,
      dataForm: {
        routids: [],
        reId: 0,
        reName: "",
        authority: "",
        purview: "",
      },
      dataRule: {
        reName: [
          { required: true, message: "角色名不能为空", trigger: "blur" },
        ],
        authority: [
          { required: true, message: "授权识别不能为空", trigger: "blur" },
        ],
        purview: [{ required: true, message: "权限不能为空", trigger: "blur" }],
      },
    };
  },
  methods: {
    /**
     *  权限
     */
    changePurview(vs) {
      /* 
        "delete", "删除",1
        "add", "新增",2
        "update", "修改",3
       */
      var str = "";
      var index = 0;
      var arr = [];
      vs.forEach((v) => {
        if (v[1] == undefined) {
          v[0] = 0;
          return;
        }
        arr.push(v);
      });
      arr.forEach((v) => {
        index++;
        var i = v[0];
        var puview = v[1];
        if (index < arr.length) {
          str += i + ":" + puview + "_";
        } else {
          str += i + ":" + puview;
        }
      });
      this.dataForm.purview = str;
    },
    /**
     *  权限查询
     */
    getListPurview() {
      this.userpurviews=[]
      api.purview().then(({ data }) => {
        this.purviews = data.data;
        this.purviews.push({id:"all",name:"全部权限",list:[{id:"all",name:"全部权限"}]})
      });
    },
  /**
   *  权限回显
   */
    purviewHuI(){
      if(!this.dataForm.purview){
        return
      }
       let arr= this.dataForm.purview.split("_");
       arr.forEach(item=>{
         var arrs= item.split(":");
        this.userpurviews.push(arrs)
      //  console.log(this.userpurviews)
      })
    },

    unique(arr, data) {
      if (!Array.isArray(arr)) {
        console.log("type error!");
        return;
      }
      let res = data;
      for (let i = 0; i < arr.length; i++) {
        if (res.indexOf(arr[i]) === -1) {
          res.push(arr[i]);
        }
      }
      return res;
    },
    changedata(v) {
      var arr = [];
      v.forEach((data) => {
        this.unique(data, arr);
      });
      arr.forEach((data) => {
        if (data == "all") {
          this.routs = [];
          this.routs.push({
            menuName: "全部权限",
            id: "all",
          });
          arr = "all";
        }
      });
      this.dataForm.authority = arr.toString();
      
      console.log(arr.toString());
    },

    //获取全部的路由
    getRoutList() {
      this.routs = [];
      this.dataForm.routids = [];
      this.getroutUser();
      rout.findAll().then((res) => {
        this.routs = res.data.data;
        this.routs.push({
          menuName: "全部权限",
          id: "all",
        });
      });
    },
    /**
     * 获取当前编辑角色的权限
     */
    getroutUser() {
      var ids = this.dataForm.authority;
      if (ids == "all") {
        this.dataForm.routids = ["all"];
      } else {
        this.dataForm.routids = ids.split(",");
      }
    },

    init(id) {
      this.getListPurview();
      this.dataForm.reId = id || 0;
      this.visible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].resetFields();
        api.info(this.dataForm.reId).then(({ data }) => {
          if (data) {
            this.dataForm.reName = data.role.reName;
            this.dataForm.authority = data.role.authority;
            this.dataForm.purview = data.role.purview;
            this.getRoutList();
           this.purviewHuI()
          }
        });
      });
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          var parms = {
            reId: this.dataForm.reId || undefined,
            reName: this.dataForm.reName,
            authority: this.dataForm.authority,
            purview: this.dataForm.purview,
          };
          api.updateAdd(parms, this.dataForm.reId).then((res) => {
            if (res) {
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.visible = false;
                  this.$emit("refreshDataList");
                },
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        }
      });
    },
  },
};
</script>
